package com.jerry.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jerry.netty.http.JerryReponse;
import com.jerry.netty.http.JerryRequest;
import com.jerry.netty.util.CustomConfig;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import org.omg.CORBA.Request;


import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Created by Shirly on 2016/12/16.handler处理器
 */
public class JerryTomcatHandler extends ChannelInboundHandlerAdapter {

    private static final Map<Pattern,Class<?>> statusMapping = new HashMap<>();

    static {
        Map map = CustomConfig.ctxPropertiesMap;
        Set<String> allkey = map.keySet();
        for (String key : allkey){
            if(key.startsWith("servlet")){
                String s = key.replaceAll("servlet.","");
                if(s.indexOf(".")!= -1){
                    s =s.substring(0,s.indexOf("."));
                }else{
                    continue;
                }
                String pattern =(String) map.get("servlet."+s+".urlPattern");
                String className = (String)map.get("servlet."+s+".className");
                pattern = pattern.replaceAll("\\*",".*");

                if(!statusMapping.containsKey(pattern)){
                    try {
                        statusMapping.put(Pattern.compile(pattern),Class.forName(className));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof HttpRequest){
            HttpRequest request = (HttpRequest)msg;
            JerryRequest request1 = new JerryRequest(ctx, request);
            JerryReponse reponse1 = new JerryReponse(ctx,request);

            String url = request1.geturl();
            String method = request1.getMethod();

            Boolean hasBoolean = false;
          for(Map.Entry<Pattern,Class<?>> entry: statusMapping.entrySet()){
                  if(entry.getKey().matcher(url).matches()){
                      StandardServlet myServlet = (StandardServlet)entry.getValue().newInstance();
                      if("get".equalsIgnoreCase(method)){
                          myServlet.doGet(request1,reponse1);
                      }else{
                          myServlet.doPost(request1,reponse1);
                      }
                      hasBoolean = true;
                      break;
                  }
            }

            if(!hasBoolean){
                String outString = String.format("本此访问时404,URL: %s ,METHOD: %s",url,method);
                reponse1.write(outString,404);
            }

        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }


}
